package com.hiyee.cart.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hiyee.api.config.ThreadLocalHolder;
import com.hiyee.api.controller.customer.CustomerControllerApi;
import com.hiyee.api.controller.goods.GoodsControllerApi;
import com.hiyee.cart.mapper.CartItemMapper;
import com.hiyee.cart.mapper.CartMapper;
import com.hiyee.idWorker.SnowflakeIdUtil;
import com.hiyee.pojo.Cart;
import com.hiyee.pojo.CartItem;
import com.hiyee.pojo.auth.CustomerTokenInfo;
import com.hiyee.pojo.repo.*;
import com.hiyee.response.ResponseJsonResult;
import com.hiyee.utils.Calculator;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 购物车数据仓储类
 *
 * @author WangBin
 */
@Repository
public class CartRepository {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private CustomerControllerApi customerControllerApi;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private SnowflakeIdUtil snowflakeIdUtil;
    @Autowired
    private GoodsControllerApi goodsControllerApi;
    @Autowired
    private CartItemMapper cartItemMapper;

    /**
     * 根据客户 id 查询购物车
     *
     * @param Long customerId
     * @return Cart
     */
    public Cart getByCustomerId(Long customerId) {
        return cartMapper.getByCustomerId(customerId);
    }

    /**
     * 创建客户空购物车
     *
     * @param Long customerId
     */
    public void createEmptyCart(Long customerId) {
        // 获取客户信息
        ResponseJsonResult responseJsonResult = customerControllerApi.getInfo(customerId);
        CustomerInfoRepo customerInfoRepo = objectMapper.convertValue(responseJsonResult.getData(), CustomerInfoRepo.class);
        // 查询客户购物车不存在则创建
        Cart cart = cartMapper.getByCustomerId(customerId);
        if(cart == null) {
            cart = new Cart();
            cart.setCartId(snowflakeIdUtil.nextId());
            cart.setCustomerId(customerId);
            cart.setFastBuy(false);
            cart.setStoreId(customerInfoRepo.getStoreId());
            cart.setCreatedAt(new Date());
            cart.setUpdatedAt(new Date());
            cart.setCustomerName(customerInfoRepo.getNickname());
            cartMapper.insertSelective(cart);
        }
    }

    /**
     * 获取购物车
     *
     * @param Long cartId
     * @return Cart
     */
    public Cart getById(Long cartId) {
        return cartMapper.getById(cartId);
    }

    /**
     * 重新计算购物车
     *
     * @param Long cartId
     */
    public void recount(Long cartId) {
        CartRecountRepo cartRecountRepo = cartItemMapper.recount(cartId);
        BigDecimal totalAmount = new BigDecimal("0.00");
        int qty = 0;
        if(cartRecountRepo != null) {
            totalAmount = cartRecountRepo.getTotalAmount();
            qty = cartRecountRepo.getQty();
        }
        cartMapper.updateTotal(cartId, totalAmount, qty);
    }

    /**
     * 获取购物车及明细数据
     *
     * @return CartInfoRepo
     */
    public CartInfoRepo getList() {
        CustomerTokenInfo customerTokenInfo = ThreadLocalHolder.get();
        CartInfoRepo cartInfoRepo = new CartInfoRepo();
        Cart cart = cartMapper.getByCustomerId(customerTokenInfo.getCustomerId());
        BeanUtils.copyProperties(cart, cartInfoRepo);
        List<CartItemRepo> cartItemRepo = cartItemMapper.getByCartId(cart.getCartId());
        cartInfoRepo.setItems(cartItemRepo);
        return cartInfoRepo;
    }

    /**
     * 获取购物车结算商品数据
     *
     * @param customerId
     * @return CartCheckoutRepo
     */
    public CartCheckoutRepo getCheckoutGoodsByCustomerId(Long customerId) {
        Cart cart = this.getByCustomerId(customerId);
        List<CartItemRepo> cartItemList = cartItemMapper.getSelectedItem(cart.getCartId());
        CartCheckoutRepo cartCheckoutRepo = new CartCheckoutRepo();
        cartCheckoutRepo.setCartId(cart.getCartId());
        cartCheckoutRepo.setCustomerId(cart.getCustomerId());
        cartCheckoutRepo.setCustomerName(cart.getCustomerName());
        cartCheckoutRepo.setStoreId(cart.getStoreId());
        cartCheckoutRepo.setTotalQty(0);
        cartCheckoutRepo.setTotalAmount(new BigDecimal("0.00"));
        cartCheckoutRepo.setCouponAmount(new BigDecimal("0.00"));
        cartCheckoutRepo.setMarketingAmount(new BigDecimal("0.00"));
        cartCheckoutRepo.setPayAmount(new BigDecimal("0.00"));
        List<CartItemRepo> cartItemRepoList = new ArrayList<>();
        for (CartItemRepo cartItem: cartItemList) {
            cartCheckoutRepo.setTotalQty(cartCheckoutRepo.getTotalQty() + cartItem.getQtyOrdered());
            cartCheckoutRepo.setTotalAmount(Calculator.add(cartCheckoutRepo.getTotalAmount(), cartItem.getTotalAmount()));
            CartItemRepo cartItemRepo = new CartItemRepo();
            BeanUtils.copyProperties(cartItem, cartItemRepo);
            cartItemRepoList.add(cartItemRepo);
        }
        cartCheckoutRepo.setItems(cartItemRepoList);
        cartCheckoutRepo.setPayAmount(cartCheckoutRepo.getTotalAmount().subtract(cartCheckoutRepo.getCouponAmount()).subtract(cartCheckoutRepo.getMarketingAmount()));
        return cartCheckoutRepo;
    }
}
